package com.rjh.concurrent.monitor;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

@Slf4j(topic = "c.ExerciseSell")
public class ExerciseSell {

    final static TicketWindow ticketWindow = new TicketWindow(20000);

    final static List<Thread> threadList = new Vector<>();
    final static List<Integer> sellCount = new Vector<>();

    // Random 为线程安全
    static Random random = new Random();
    // 随机 1~5
    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }

    public static void main(String[] args) throws InterruptedException {
        for(int i=0;i<20000;i++){
            Thread thread = new Thread(()->{
                int sell = ticketWindow.sell(randomAmount());
                sellCount.add(sell);
            });
            thread.start();
            threadList.add(thread);
        }

        for (Thread thread : threadList) {
            thread.join();
        }

        // 买出去的票求和
        log.debug("selled count:{}",sellCount.stream().mapToInt(c -> c).sum());
        // 剩余票数
        log.debug("remainder count:{}", ticketWindow.getCount());
    }
}

/**
 * 买票窗口
 */
class TicketWindow{

    private int count;

    public TicketWindow(int count){
        this.count = count;
    }

    public int getCount() {
        return count;
    }

    public int sell(int num){
        if (num > this.count){
            return 0;
        }
        this.count -= num;
        return num;
    }
}